package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private TaskService taskService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }


    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    // 查看流程高亮节点
    @Override
    public InputStream getByAuditId(Long id) {
        CarPackageAudit audit = this.get(id);
        String instanceId = audit.getInstanceId();
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmninfoId());
        List<String> highLightedActivities = null;
        // 如果在审核中, 需要高亮目前运行节点
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            // 根据流程实例ID 获取运行节点
            highLightedActivities = runtimeService.getActiveActivityIds(instanceId);

        } else {
            // 如果是审核通过, 不需要高亮节点
            highLightedActivities = new ArrayList<>();
        }

        // 资源管理器, 存储流程定义的id
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();

        return generator.generateDiagram(bpmnModel,highLightedActivities, Collections.EMPTY_LIST,"宋体", "宋体", "宋体");
    }

    // 撤销
    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = this.get(id);
        // 将审核状态改为撤销
        carPackageAuditMapper.changeAuditStatus(id, CarPackageAudit.STATUS_CANCEL);
        // 修改审核状态为初始状态
        serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"撤销审核");

    }

    // 确认审批
    @Override
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        CarPackageAudit audit = this.get(id);
        // 如果流程处于审批中才可以进行操作
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("非法操作, 只有审批中的状态才能执行操作");
        }
        // 只有节点处理人才能对这个记录进行审核
        if (!ShiroUtils.getUserId().equals(audit.getAuditorId())){
            throw new BusinessException("非法操作, 只有节点处理人才能执行操作");
        }
        String userName = ShiroUtils.getUser().getUserName();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            // 审核通过
            info = userName +"[同意], 批注意见:"+info;

        } else {
            info = userName +"[拒绝],批注意见:"+info;
        }
        audit.setInfo(audit.getInfo()+"</br>"+info);

        // 根据流程定义id获取任务对象
        Task task = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        // 在任务上设置变量。如果变量不存在，它将在最外层范围内创建。这意味着在此任务与执行相关的情况下的流程实例。
        taskService.setVariable(task.getId(),"auditStatus",auditStatus);
        // 向任务和/或流程实例添加注释
        taskService.addComment(task.getId(),audit.getInstanceId(),info);
        // 要完成的任务的id, 完成任务
        taskService.complete(task.getId());

        // 获取下一个节点
        Task nextTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            if (nextTask != null){  // 有下一个节点
                // 财务审核
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
                audit.setAuditTime(new Date());
            } else { // 没有下一个节点, 表示审核通过, 流程结束
                serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED); // 审核通过
                audit.setStatus(CarPackageAudit.STATUS_PASS);   // 审核通过
            }
        } else {    // 审核拒绝
            // 修改服务单项审核状态为初始化状态
            serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
            // 设置审核记录的审核装
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
        }
        carPackageAuditMapper.updateByPrimaryKey(audit);
    }
}
